﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace TestUp.Models.Helpers
{
    public class UserInfoHelper
    {
        public List<UserInfo> GetAllUserInfoes()
        {
            return DataWorkItem.Entity.UserInfoes.ToList();
        }

        public UserInfo GetUserInfo(int userId)
        {
            return DataWorkItem.Entity.UserInfoes.FirstOrDefault(x => x.UserId == userId);
        }

        public UserInfo GetUserInfo(string userName)
        {
            return DataWorkItem.Entity.UserInfoes.FirstOrDefault(x => x.UserName == userName);
        }

        public bool LogIn(string userName, string password)
        {
            var userInfo = DataWorkItem.Entity.UserInfoes.FirstOrDefault(x => x.UserName == userName && x.Password == password);
            if (userInfo != null)
            {
                userInfo.IsLoggedIn = true;
                DataWorkItem.Entity.SaveChanges();
                return true;
            }
            return false;
        }

        public void LogOff(string userName)
        {
            var userInfo = GetUserInfo(userName);
            if (userInfo != null)
            {
                userInfo.IsLoggedIn = false;
                DataWorkItem.Entity.SaveChanges();
            }
        }

        public void DeleteUserInfo(int userId)
        {
            var userInfo = GetUserInfo(userId);
            if(userInfo!=null)
            {
                DataWorkItem.Entity.UserInfoes.Remove(userInfo);
                DataWorkItem.Entity.SaveChanges();
            }
        }

        public void UpdateUserInfo(UserInfo userInfo)
        {
            var originalUserInfo = GetUserInfo(userInfo.UserId);
            if (originalUserInfo != null)
            {
                //Update fields
                originalUserInfo.UserName = userInfo.UserName;
                originalUserInfo.Password = userInfo.Password;
                originalUserInfo.PermissionId = userInfo.PermissionId;
                originalUserInfo.FirstName = userInfo.FirstName;
                originalUserInfo.LastName = userInfo.LastName;
                originalUserInfo.GroupId = userInfo.GroupId;

                DataWorkItem.Entity.SaveChanges();
            }
        }

        public void CreateUserInfo(UserInfo sourceUserInfo)
        {
            var newUserInfo = new UserInfo
            {
                UserName = sourceUserInfo.UserName,
                Password = sourceUserInfo.Password,
                PermissionId =sourceUserInfo.PermissionId,
                FirstName = sourceUserInfo.FirstName,
                LastName = sourceUserInfo.LastName,
                GroupId = sourceUserInfo.GroupId,
                RegistrationDate = DateTime.Now
            };
            DataWorkItem.Entity.UserInfoes.Add(newUserInfo);
            DataWorkItem.Entity.SaveChanges();
        }
    }
}